package com.xb.demo.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class IPAddrUtils {
    public static String getIpAddr(HttpServletRequest req) {
        String ip = req.getHeader("x-forwarded-for");
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = req.getHeader("Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = req.getHeader("WL-Proxy-Client-IP");
        }
        if ((ip == null) || (ip.length() == 0) || ("unknown".equalsIgnoreCase(ip))) {
            ip = req.getRemoteAddr();
            if (ip.equals("127.0.0.1")) {
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ip = inet.getHostAddress();
            }
        }
        if ((ip != null) && (ip.length() > 15) &&
                (ip.indexOf(",") > 0)) {
            ip = ip.substring(0, ip.indexOf(","));
        }

        //
//        if (ip.contains(",")) {
//            String [] ips= ip.split(",");
//        }

        return ip;
    }


    public static String getIp1(HttpServletRequest req) {
        String ip = req.getHeader("x-forwarded-for")==null?"":req.getHeader("x-forwarded-for");
        return ip;
    }

    public static String getIp2(HttpServletRequest req) {
        String ip = req.getHeader("Proxy-Client-IP")==null?"":req.getHeader("x-forwarded-for");
        return ip;
    }
    public static String getIp3(HttpServletRequest req) {
        String ip = req.getHeader("WL-Proxy-Client-IP")==null?"":req.getHeader("x-forwarded-for");
        return ip;
    }
    public static String getIp4(HttpServletRequest req) {
        String ip = req.getRemoteAddr()==null?"":req.getHeader("x-forwarded-for");
        return ip;
    }
    public static String getIp5(HttpServletRequest req) {
        String ip = req.getHeader("X-Real-IP")==null?"":req.getHeader("x-forwarded-for");
        return ip;
    }


}
